import { NavigationGuardNext, RouteLocationNormalized } from 'vue-router'
import router from '@/router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import useUserStore from '@/store/modules/user'
import pinia from '@/store'
import setting from '@/setting'

// 不显示进度圆圈
nprogress.configure({ showSpinner: false })

const userStore = useUserStore(pinia)

// 全局守卫: 项目当中任意路由切换都会触发的钩子
// 全局前置守卫
router.beforeEach(
  async (
    to: RouteLocationNormalized,
    from: RouteLocationNormalized,
    next: NavigationGuardNext,
  ) => {
    console.log('beforeEach: ', to, from, next)
    nprogress.start()

    const token = userStore.token
    const username = userStore.username
    if (token) {
      // 存在有效token
      if (username) {
        // 存在有效用户信息
        next()
      } else {
        // 不存在有效用户信息, 尝试获取
        try {
          await userStore.userInfo()
          next()
        } catch (e) {
          // 获取失败则跳转首页
          await userStore.userLogout()
          next({ path: '/', query: { redirect: to.path } })
        }
      }
    } else {
      if (to.path === '/login') {
        // 未登录时访问登录页面直接放行
        next()
      } else {
        // 未登录时访问非登录页面跳转登录页面
        next({ path: '/login', query: { redirect: to.path } })
      }
    }
  },
)

// 全局后置守卫

router.afterEach(
  (to: RouteLocationNormalized, from: RouteLocationNormalized) => {
    console.log('afterEach: ', to, from)
    nprogress.done()
    document.title = `${setting.title} - ${to.meta.title}`
  },
)
